package cn.yto.print.utils;

import cn.yto.print.constants.AssistantConstants;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.Socket;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

public class CommonUtil {

    private static final Logger logger = LogManager.getLogger(CommonUtil.class);

    /**
     * 获取当前项目路径
     */
    public static String getCurrentDir(String subDir) {
        final String basePath = System.getProperty("user.dir");
        if (StringUtils.isBlank(subDir)) {
            return basePath;
        }
        String separator = "\\";
        return basePath + separator + subDir;
    }

    /**
     * 获取路径的父路径
     */
    public static String getParentPath(String fullPath) {
        if (StringUtils.isEmpty(fullPath)) {
            return fullPath;
        }
        int lastBackslashIndex = fullPath.lastIndexOf("\\");
        return (lastBackslashIndex >= 0) ? fullPath.substring(0, lastBackslashIndex) : fullPath;
    }

    /**
     * 从 URL 中提取文件名
     */
    public static String getFileNameFromUrl(String urlString) {
        try {
            URL parsedUrl = new URL(urlString);
            String rawPath = parsedUrl.getPath();
            Path path = Paths.get(rawPath);
            String fileName = path.getFileName().toString();
            return URLDecoder.decode(fileName, "UTF-8");
        } catch (Exception e) {
            logger.error("解析 URL 发生异常", e);
            return null;
        }
    }

    public static String getAppConfig(String key) {
        try (InputStream input = Thread.currentThread()
                .getContextClassLoader()
                .getResourceAsStream("application.properties")) {
            if (input == null) {
                return "";
            }
            Properties prop = new Properties();
            prop.load(input);
            return StringUtils.trimToEmpty(prop.getProperty(key));
        } catch (Exception ex) {
            return "";
        }
    }

    /**
     * 通过 socket 显示窗口
     */
    public static void activeRunInstance(String host, String port) {
        int parsedPort;
        try {
            parsedPort = Integer.parseInt(port);
        } catch (NumberFormatException e) {
            logger.error("端口格式错误: {}", port, e);
            return;
        }
        try (Socket socket = new Socket(host, parsedPort);
             DataOutputStream out = new DataOutputStream(socket.getOutputStream())) {
            out.writeUTF(AssistantConstants.SHOW_COMMAND);
            out.flush();
            socket.shutdownOutput();
        } catch (Exception e) {
            logger.error("连接正在运行的小助手服务实例异常", e);
        }
    }

    public static void gracefulShutdown(ExecutorService executor) {
        if (executor == null) {
            return;
        }
        if (executor.isShutdown()) {
            return;
        }
        try {
            executor.shutdown();
            boolean terminated = executor.awaitTermination(2, TimeUnit.SECONDS);
            if (!terminated) {
                executor.shutdownNow();
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            executor.shutdownNow();
        }
    }

}
